package com.kevin.protocol;

import com.kevin.core.RpcProtocol;
import com.kevin.core.RpcRequest;
import com.kevin.handler.RpcClientInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyClient {
    private String ip;
    private int port;
    private Bootstrap bootstrap;
    private EventLoopGroup eventLoop = new NioEventLoopGroup();


    public NettyClient(String ip, int port) {
        this.bootstrap = new Bootstrap();
        bootstrap.group(eventLoop).channel(NioSocketChannel.class)
                .handler(new RpcClientInitializer());

        this.ip=ip;
        this.port=port;
    }


    public void sendRequest(RpcProtocol<RpcRequest> rpcRequestRpcProtocol){
        try {
            final ChannelFuture channelFuture = bootstrap.connect(this.ip, this.port).sync();
            channelFuture.addListener(listener->{
                if(channelFuture.isSuccess()){
                    log.info("client connect success");
                }else{
                    channelFuture.cause().printStackTrace();
                    eventLoop.shutdownGracefully();
                }
            });
            channelFuture.channel().writeAndFlush(rpcRequestRpcProtocol);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
